package org.six11.olive.collabclient.server;

import java.util.Map;
import java.util.Set;
import java.util.HashSet;
import org.six11.util.io.Message;
import org.six11.util.adt.MultiState;
import org.six11.util.adt.SynchronizedQueue;

public class StateTool {
  protected MultiState state;

  public StateTool(MultiState state) {
    this.state = state;
  }

  @SuppressWarnings("unchecked")
  protected SynchronizedQueue<Message> getMessageQueue(String sessionID, boolean createIfNecessary) {
    Map<String, SynchronizedQueue<Message>> queues = (Map<String, SynchronizedQueue<Message>>) 
      state.getValue("message queues");
    if (!queues.containsKey(sessionID) && createIfNecessary) {
      queues.put(sessionID, new SynchronizedQueue<Message>());
    }
    SynchronizedQueue<Message> q = queues.get(sessionID);
    return q;
  }

  @SuppressWarnings("unchecked")
  protected void addSessionToRoom(String sessionID, String roomName) {
    removeSessionFromRoom(sessionID);
    Map<String, String> sessionToRoom = (Map<String, String>) state.getValue("session to room");
    sessionToRoom.put(sessionID, roomName);
    Set<String> roomMembership = getRoomMembership(roomName, true);
    roomMembership.add(sessionID);
  }

  @SuppressWarnings("unchecked")
  protected void removeSessionFromRoom(String sessionID) {
    Map<String, String> sessionToRoom = (Map<String, String>) state.getValue("session to room");
    if (sessionToRoom.containsKey(sessionID)) {
      String roomName = sessionToRoom.get(sessionID);
      Set<String> members = getRoomMembership(roomName, false);
      if (members != null) {
	members.remove(sessionID);
	if (members.size() == 0) {
	  Map<String, Set<String>> roomMembership = (Map<String, Set<String>>) state.getValue("room membership");
	  roomMembership.remove(roomName);
	}
      }
    }
    sessionToRoom.remove(sessionID);
  }

  @SuppressWarnings("unchecked")
  protected String getRoomForSession(String sessionID) {
    Map<String, String> sessionToRoom = (Map<String, String>) state.getValue("session to room");
    return sessionToRoom.get(sessionID);
  }

  @SuppressWarnings("unchecked")
  protected Set<String> getRoomMembership(String roomName, boolean createIfNecessary) {
    Map<String, Set<String>> roomMembership = (Map<String, Set<String>>) state.getValue("room membership");
    if (!roomMembership.containsKey(roomName) && createIfNecessary) {
      roomMembership.put(roomName, new HashSet<String>());
    }
    return roomMembership.get(roomName);
  }

}
